package com.lxp.userms.service.impl;

import com.lxp.userms.entity.Post;
import com.lxp.userms.mapper.PostMapper;
import com.lxp.userms.service.CommentService;
import com.lxp.userms.service.FavoriteService;
import com.lxp.userms.service.LikeService;
import com.lxp.userms.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService; // 注入 LikeService

    @Autowired
    private FavoriteService favoriteService;
    @Override
    @Transactional
    public int publishPost(Post post) {
        return postMapper.insertPost(post);
    }

    @Override
    public Post getPostById(int id) {
        return postMapper.selectPostById(id);
    }

    @Override
    public List<Post> getAllPosts() {
        return postMapper.selectAllPosts();
    }

    @Override
    public List<Post> getPostsByUserId(int userId) {
        return postMapper.selectPostsByUserId(userId);
    }
    @Override
    public List<Post> getPostsByCategoryId(int categoryId) {
        return postMapper.selectPostsByCategoryId(categoryId);
    }

    @Override
    public List<Post> searchPostsByKeyword(String keyword) {
        return postMapper.searchPostsByKeyword(keyword);
    }


    @Override
    @Transactional
    public int updatePost(Post post) {
        return postMapper.updatePost(post);
    }

    @Override
    @Transactional
    public int deletePost(int id) {
        // 删除与 Post 相关的 Like 记录
        likeService.deleteLikesByPostId(id);

        // 删除与 Post 相关的 Favorite 记录
        favoriteService.deleteFavoritesByPostId(id);

        // 删除 Post 本身
        return postMapper.deletePost(id);
    }

    @Override
    @Transactional
    public int deletePostsByCategoryId(int categoryId) {
        return postMapper.deletePostsByCategoryId(categoryId);
    }
}